import string, urllib, time, thread

def gsweb_player_worker_thread(threadName, pid): #look up rank and other player specific stats from the web
    # global thread communication variables and thier associated mutual exclusion locks
    global numThreads, numThreadsLock, serversLock, totalThreads
    
    t1 = time.time()

    gamespy_url = string.Template("http://bf2web.gamespy.com/ASP/getplayerinfo.aspx?pid=$pid&info=per*,cmb*,twsc,cpcp,cacp,dfcp,kila,heal,rviv,rsup,rpar,tgte,dkas,dsab,cdsc,rank,cmsc,kick,kill,deth,suic,ospm,klpm,klpr,dtpr,bksk,wdsk,bbrs,tcdr,ban,dtpm,lbtl,osaa,vrk,tsql,tsqm,tlwf,mvks,vmks,mvn*,vmr*,fkit,fmap,fveh,fwea,wtm-,wkl-,wdt-,wac-,wkd-,vtm-,vkl-,vdt-,vkd-,vkr-,atm-,awn-,alo-,abr-,ktm-,kkl-,kdt-,kkd-")

    (keys, values) = urllib.urlopen(gamespy_url.safe_substitute(pid=pid)).readlines()[3:5]

    #print threadName+": keys = " + keys
    #print threadName+": values = " + values

    serversLock.acquire()
    player = dict(zip(keys.split()[1:], values.split()[1:]))
    serversLock.release()

    numThreadsLock.acquire()
    numThreads-=1
    numThreadsLock.release()
    print "%.2f seconds elapsed in gsweb_player_worker_thread() %d" % (time.time() - t1, numThreads)


numThreadsLock = thread.allocate_lock()
serversLock = thread.allocate_lock()
numThreads = 0
totalThreads = 0
numThreadsTarget = 50
sleeptime = .016

try:
    t1 = time.time()

    while True:
#         if numThreads > numThreadsTarget :
#             sleeptime += .010
#         else:
#             sleeptime -= .001
        if sleeptime < 0: sleeptime = 0
        while numThreads > numThreadsTarget:
            #print "exceeded numThreadsTarget"
            pass
        time.sleep(sleeptime)
        numThreadsLock.acquire()
        numThreads+=1
        totalThreads += 1
        numThreadsLock.release()
        thread.start_new_thread(gsweb_player_worker_thread, ("Thread_", "136897090"))
        #print "numThreads = %3d sleeptime = %.4f" % (numThreads, sleeptime)
    
    while numThreads != 0: pass
except KeyboardInterrupt:
    print "average througput = %f players per second." % (totalThreads / (time.time() - t1))
    raise